//
//  MyOrderController.m
//  Japanese+
//
//  Created by ccdaguo on 15/11/1.
//  Copyright © 2015年 SSIC. All rights reserved.
//

#import "MyOrderViewController.h"
#import "MyOrderCell.h"
#import "MyOrderModel.h"

#import "ChatViewController.h"
#import "UserProfileManager.h"

@interface MyOrderViewController ()<UITableViewDelegate,UITableViewDataSource,MyOrderCellDelegate>

@end

@implementation MyOrderViewController
{
    VOSegmentedControl *_segment;
    UITableView * _tableView;
    
    MemberModel *_memberModel;
    TeacherModel *_teacherModel;
    NSMutableArray *_dataArray;
    NSInteger _pageIndex;
    MyOrderModel *_myOrderModel;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatNavigationBarWithImage:nil title:@"我的订单"];
    [self creatNavigationBarLeftItemWithLeftTitle:nil LeftImage:ECIMAGENAME(@"back_button.png")];

    [self creatSegmentController];
    [self creatTableView];
}


- (void)viewWillAppear:(BOOL)animated
{
    [self loadUserInfo];
    [self segmentClick:_segment];
}

- (void)leftBtnClick:(id)leftSender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)loadUserInfo
{
    UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
    [userInfo loadUserInfoFromSanbox];
    _memberModel = userInfo.memberModel;
    _teacherModel = userInfo.teacherModel;
}


- (void)creatFirstHttpRequest
{
    NSDictionary *param = @{
                            @"t_member_Id":_memberModel.member_Id,
                            @"promulgator_mark":@"1",
                            @"pageIndex":[NSString stringWithFormat:@"%ld",_pageIndex],
                            @"pageSize":@"10",
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(ORDER_LP) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            [MyOrderModel setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data":@"MyOrderData",
                         };
            }];
            
            if (_dataArray) {
                if (_tableView.mj_header.isRefreshing) {
                    [_dataArray removeAllObjects];
                }
            }else{
                _dataArray = [[NSMutableArray alloc] init];
            }
            
            _myOrderModel = [[MyOrderModel alloc] init];
            _myOrderModel = [MyOrderModel objectWithKeyValues:result];
            
            [_dataArray addObjectsFromArray:_myOrderModel.data];
            [_tableView reloadData];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }else{
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }
    }];
}


- (void)creatSecondHttpRequest
{
    NSDictionary *param = @{
                            @"t_member_Id":_memberModel.member_Id,
                            @"promulgator_mark":@"1",
                            @"pageIndex":[NSString stringWithFormat:@"%ld",_pageIndex],
                            @"pageSize":@"10",
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(ORDER_P) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            [MyOrderModel setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data":@"MyOrderData",
                         };
            }];
            
            if (_dataArray) {
                if (_tableView.mj_header.isRefreshing) {
                    [_dataArray removeAllObjects];
                }
            }else{
                _dataArray = [[NSMutableArray alloc] init];
            }
            
            _myOrderModel = [[MyOrderModel alloc] init];
            _myOrderModel = [MyOrderModel objectWithKeyValues:result];
            
            [_dataArray addObjectsFromArray:_myOrderModel.data];
            [_tableView reloadData];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }else{
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }
    }];
}

- (void)creatThirdHttpRequest
{
    NSDictionary *param = @{
                            @"t_member_Id":_memberModel.member_Id,
                            @"promulgator_mark":@"1",
                            @"pageIndex":[NSString stringWithFormat:@"%ld",_pageIndex],
                            @"pageSize":@"10",
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(ORDER_C) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            [MyOrderModel setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data":@"MyOrderData",
                         };
            }];
            
            if (_dataArray) {
                if (_tableView.mj_header.isRefreshing) {
                    [_dataArray removeAllObjects];
                }
            }else{
                _dataArray = [[NSMutableArray alloc] init];
            }
            
            _myOrderModel = [[MyOrderModel alloc] init];
            _myOrderModel = [MyOrderModel objectWithKeyValues:result];
            
            [_dataArray addObjectsFromArray:_myOrderModel.data];
            [_tableView reloadData];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }else{
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }
    }];
}

- (void)creatFourthHttpRequest
{
    NSDictionary *param = @{
                            @"t_member_Id":_memberModel.member_Id,
                            @"promulgator_mark":@"1",
                            @"pageIndex":[NSString stringWithFormat:@"%ld",_pageIndex],
                            @"pageSize":@"10",
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(ORDER_LC) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            [MyOrderModel setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data":@"MyOrderData",
                         };
            }];
            
            if (_dataArray) {
                if (_tableView.header.isRefreshing) {
                    [_dataArray removeAllObjects];
                }
            }else{
                _dataArray = [[NSMutableArray alloc] init];
            }
            
            _myOrderModel = [[MyOrderModel alloc] init];
            _myOrderModel = [MyOrderModel objectWithKeyValues:result];
            
            [_dataArray addObjectsFromArray:_myOrderModel.data];
            [_tableView reloadData];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }else{
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }
    }];
}

- (void)creatSegmentController
{
    _segment = [[VOSegmentedControl alloc] initWithSegments:@[@{
                                                                  @"text":@"待支付"
                                                                  },@{
                                                                  @"text":@"已支付"
                                                                  },@{
                                                                  @"text":@"已取消"
                                                                  },@{
                                                                  @"text":@"待评价"
                                                                  }]];
    _segment.frame = CGRectMake(0, 64, ECSCREEN_W, 40);
    _segment.animationType = VOSegCtrlAnimationTypeSmooth;
    _segment.contentStyle = VOContentStyleTextAlone;
    _segment.indicatorStyle = VOSegCtrlIndicatorStyleBottomLine;
    _segment.allowNoSelection = NO;
    _segment.scrollBounce = NO;
    _segment.selectedTextFont = [UIFont systemFontOfSize:15];
    _segment.selectedIndicatorColor = NAVC_COLOR;
    _segment.textColor = ECCOLOR(0, 0, 0, 1);
    _segment.selectedTextColor = NAVC_COLOR;
    _segment.selectedBackgroundColor = ECCOLOR(255, 255, 255, 1);
    _segment.backgroundColor = ECCOLOR(255, 255, 255, 255);
    _segment.indicatorThickness = 2;
    _segment.indicatorCornerRadius = 15;
    _segment.selectedSegmentIndex = self.index;
    [_segment addTarget:self action:@selector(segmentClick:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_segment];
}


- (void)segmentClick:(VOSegmentedControl *)segment
{
    [_tableView.mj_header beginRefreshing];
}

- (void)creatTableView
{
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 104, ECSCREEN_W, ECSCREEN_H - 104) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.backgroundColor = BG_COLOR;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    
    _tableView.tableFooterView = [[UIView alloc]init];
    
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [self.view addSubview:_tableView];
}

- (void)headerRefresh
{
    _pageIndex = 0;
    switch (_segment.selectedSegmentIndex) {
        case 0:
        {
            [self creatFirstHttpRequest];
        }
            break;
        case 1:
        {
            [self creatSecondHttpRequest];
        }
            break;
        case 2:
        {
            [self creatThirdHttpRequest];
        }
            break;
        case 3:
        {
            [self creatFourthHttpRequest];
        }
            break;

            
        default:
            break;
    }
}

- (void)footerRefresh
{
    if (_dataArray.count%10  == 0) {
        _pageIndex++;
        switch (_segment.selectedSegmentIndex) {
            case 0:
            {
                [self creatFirstHttpRequest];
            }
                break;
            case 1:
            {
                [self creatSecondHttpRequest];
            }
                break;
            case 2:
            {
                [self creatThirdHttpRequest];
            }
                break;
            case 3:
            {
                [self creatFourthHttpRequest];
            }
                break;
                
                
            default:
                break;
        }
    }else{
        [_tableView.mj_footer endRefreshingWithNoMoreData];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130.f;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ECSCREEN_W, 5)];
    view.backgroundColor = BG_COLOR;
    return view;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuseIdentifier = @"myOrderCell";
    MyOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (nil == cell) {
        NSArray *arr = [[NSBundle mainBundle]loadNibNamed:@"MyOrderCell" owner:nil options:nil];
        for (NSObject *obj in arr) {
            if ([obj isKindOfClass:[MyOrderCell class]]) {
                cell = (MyOrderCell *)obj;
                if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                    [cell setSeparatorInset:UIEdgeInsetsZero];
                }
                if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                    [cell setLayoutMargins:UIEdgeInsetsZero];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                break;
            }
        }
    }
    
    [cell setCellWithModel:_dataArray WithIndexPath:indexPath WithSegment:_segment.selectedSegmentIndex];
    cell.delegate = self;
    return cell;
}


- (void)myOrderCell:(MyOrderCell *)cell commentClick:(UIButton *)comment
{
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    NSLog(@"----%ld----评论",indexPath.section);

}

- (void)myOrderCell:(MyOrderCell *)cell chatClick:(UIButton *)chat
{
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    NSLog(@"----%ld----聊天",indexPath.section);
    MyOrderData *data = _dataArray[indexPath.section];
    
    NSDictionary *loginInfo = [[[EaseMob sharedInstance] chatManager] loginInfo];
    NSString *loginUsername = [loginInfo objectForKey:kSDKUsername];
    if (loginUsername && loginUsername.length > 0) {
        if ([loginUsername isEqualToString:data.mobile]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:NSLocalizedString(@"friend.notChatSelf", @"can't talk to yourself") delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
            [alertView show];
            
            return;
        }
    }

    ChatViewController *chatVC = [[ChatViewController alloc] initWithChatter:data.mobile isGroup:NO];
    chatVC.title = [[UserProfileManager sharedInstance] getNickNameWithUsername:data.mobile];
    [self.navigationController pushViewController:chatVC animated:YES];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
